package com.sf.gis.boot.rcboot.shiro;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sf.gis.boot.rcboot.constants.Common;
import com.sf.gis.boot.rcboot.shiro.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * @author 80004819
 * @ClassName:
 * @Description:
 * @date 2020年09月14日 15:10:11
 */
@Slf4j
public class ShiroUtil {


    /**
     * 获取subject
     *
     * @return
     */
    public static Subject getSubject() {
        try {
            Subject subject = SecurityUtils.getSubject();
            return subject;
        } catch (Exception e) {
            log.error("未登录", e);
            return null;
        }
    }


    public static Session getSession() {
        return getSubject().getSession();
    }

    protected Session getSession(Boolean flag) {
        return getSubject().getSession(flag);
    }


    /**
     * 从 token中获取用户名
     *
     * @return token中包含的用户名
     */
    public static String getUsername() {
        return getUsername(null);
    }

    public static String getUsername(String token) {
        SysUser sysUser = getUserInfo(token);
        return StrUtil.isNotBlank(sysUser.getUsername()) ? sysUser.getUsername() : null;
    }

    /**
     * 将token解密成json对象
     *
     * @param token
     * @return
     */
    public static SysUser getUserInfo(String token) {
        if (StrUtil.isEmpty(token)) {
            if (null == getSubject() || null == getSubject().getPrincipal()) return null;
            token = getSubject().getPrincipal().toString();
        }
        try {
            DecodedJWT jwt = JWT.decode(token);
            String userinfo = jwt.getClaim("userinfo").asString();
            // JsonObject info = Common.GSON.fromJson(userinfo, JsonObject.class);
            SysUser sysUser = Common.GSON.fromJson(userinfo, SysUser.class);
            return sysUser;
        } catch (JWTDecodeException e) {
            log.error("error：{}", e.getMessage());
            return null;
        }
    }


}
